package cn.controller;


import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.common.ExceResult;
import cn.common.LayTable;
import cn.common.PageString;
import cn.filter.LoginCheck;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.entity.usualassessment.UsAssTempCreateIndexEntity;
import cn.kpi.entity.usualassessment.UsAssTemplateEntity;
import cn.kpi.entity.usualassessment.UsAssTemplateIndexEntity;
import cn.kpi.entity.usualassessment.UserTemplateEntity;
import cn.kpi.entity.usualassessment.UserUsAssTempEntity;
import cn.kpi.service.usualassessment.IUsAssTemplateService;
import cn.kpi.service.usualassessment.IUserTempService;
import cn.kpi.service.usualassessment.IUserUsAssTempService;

@Controller
@RequestMapping("usertemp")
public class UserTempController extends BaseController {
	
	@Autowired
	private IUserTempService iUserTempService;
	
	@Autowired
	private IUsAssTemplateService iUsAssTemplateService;
	
	@Autowired
	private IUserUsAssTempService iUserUsAssTempService;

	@RequestMapping(value = "/user_temp_list")
	public String UserTempList(Model model) {
		try{
		}
		catch(Exception ex){
			
		}
		return "usualassessment/user_temp_list";
	}
	
	@RequestMapping(value = "/user_temp_useryy")
	public String user_temp_useryy(Model model,Long templateid,Long groupid,Long szdw) {
		try{
			model.addAttribute("templateid", templateid);
			model.addAttribute("groupid", groupid);
			model.addAttribute("szdw", szdw);
		}
		catch(Exception ex){
			
		}
		return "usualassessment/user_temp_useryy";
	}
	
	
	
	@RequestMapping(value = "/user_temp_addtemp")
	public String UserTempAddTemp(Model model,Long templateid) {
		try{
			model.addAttribute("templateid", templateid);
		}
		catch(Exception ex){
			
		}
		return "usualassessment/user_temp_addtemp";
	}
	
	@RequestMapping(value = "/user_temp_edittemp")
	public String UserTempEditTemp(Model model,Long templateid,Long groupid) {
		try{
			String where="";
			
			//if(templateid>0){
				UsAssTemplateEntity ustempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);
				model.addAttribute("ustempentity", ustempentity);
			//}
			
			String orgids=this.GetOrgListByRole();
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			  java.util.Date dt1 = ustempentity.getCreatetime();
			  java.util.Date dt2 = df.parse("2018-08-01");
	          if(dt1.getTime()<dt2.getTime()){
	        	  where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")) AND groupid="+groupid+" ";
	          }
	          else{
	        	  where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")) AND groupid="+groupid+" AND templateid="+templateid+" ";
	          }
			
			
			
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpanByTempIdAndWhere(templateid,where);
			model.addAttribute("lst", lst);
			model.addAttribute("templateid", templateid);
			model.addAttribute("groupid", groupid);
			
			
			String parentid = "";
			String usassid = "";
			for (int i = 0; i < lst.size(); i++) {
				UsAssTemplateIndexEntity entity = lst.get(i);
				usassid += entity.getAssindexid().toString() + ",";
				if (parentid.length() > 0) {
					String[] strarr = parentid.split(",");
					String last = strarr[strarr.length - 1];
					if (!last.equals(entity.getParentid().toString())) {
						parentid += entity.getParentid().toString() + ",";
					}
				} else {
					parentid += entity.getParentid().toString() + ",";
				}

			}
			PageString pagestring = new PageString();
			pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
			pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
			model.addAttribute("pagestring", pagestring);
			
			
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "usualassessment/user_temp_edittemp";
	}
	
	
	@RequestMapping(value = "/user_temp_show")
	public String user_temp_show(Model model,Long templateid,Long groupid) {
		try{
			String where="";
			
			//if(templateid>0){
				UsAssTemplateEntity ustempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);
				model.addAttribute("ustempentity", ustempentity);
			//}
			
			String orgids=this.GetOrgListByRole();
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			
			  java.util.Date dt1 = ustempentity.getCreatetime();
			  java.util.Date dt2 = df.parse("2018-08-01");
	          if(dt1.getTime()<dt2.getTime()){
	        	  where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")) AND groupid="+groupid+" ";
	          }
	          else{
	        	  where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")) AND groupid="+groupid+" AND templateid="+templateid+" ";
	          }
			
			
			
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListRowSpanByTempIdAndWhere(templateid,where);
			model.addAttribute("lst", lst);
			model.addAttribute("templateid", templateid);
			model.addAttribute("groupid", groupid);
			
			
			String parentid = "";
			String usassid = "";
			for (int i = 0; i < lst.size(); i++) {
				UsAssTemplateIndexEntity entity = lst.get(i);
				usassid += entity.getAssindexid().toString() + ",";
				if (parentid.length() > 0) {
					String[] strarr = parentid.split(",");
					String last = strarr[strarr.length - 1];
					if (!last.equals(entity.getParentid().toString())) {
						parentid += entity.getParentid().toString() + ",";
					}
				} else {
					parentid += entity.getParentid().toString() + ",";
				}

			}
			PageString pagestring = new PageString();
			pagestring.setKeyword1(parentid.substring(0, parentid.length() - 1));
			pagestring.setKeyword2(usassid.substring(0, usassid.length() - 1));
			model.addAttribute("pagestring", pagestring);
			
			
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return "usualassessment/user_temp_show";
	}
	
	
	
	@RequestMapping(value = "/user_temp_addindex")
	public String UserTempAddindex(Model model,Long assindexid,Long groupid,Long templateid) {
		try {
			String where = " AND assindextype=0";
			if(this.GetLoginUserId()==0){
				where+=" AND byuserid=0";
			}
			else{
				String orgids=this.GetOrgListByRole();
				where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			}
			
			List<UsAssTemplateIndexEntity> lst = iUsAssTemplateService.GetTemplateIndexListByWhere(where);
			model.addAttribute("lst", lst);
			UsAssTemplateIndexEntity entity=new UsAssTemplateIndexEntity();
			if(assindexid>0){
			  entity=iUsAssTemplateService.GetIndexById(assindexid);
			}
			else{
				entity.setParentid(0L);
			}
			model.addAttribute("entity", entity);
			model.addAttribute("groupid", groupid);
			
			model.addAttribute("templateid", templateid);
			
			
			UserEntity userentity=this.GetLoginUser();
			
			//List<OrgEntity> lstorg = iOrgService.GetOrgListByWhere(" AND orgtype=1 AND  orgparentid="+userentity.getSzdw());
			//model.addAttribute("lstorg", lstorg);
			
		} catch (Exception ex) {

		}
		return "usualassessment/user_temp_addindex";
	}
	
	
	@LoginCheck(description = true)
	@ResponseBody
	@RequestMapping(value = "/get_list")
	public LayTable<UsAssTemplateEntity> GetList(HttpServletRequest request) {

		List<UsAssTemplateEntity> lst=null;
		LayTable<UsAssTemplateEntity> layTable=new LayTable<UsAssTemplateEntity>();
		try {
			String templatename = request.getParameter("templatename");
			
			String where="";
			if(templatename!=null&&templatename.length()>0){
				where+=" AND templatename LIKE '%"+templatename.trim()+"%'";
			}
			
			String orgids=this.GetOrgListByRole();
			where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			
			int page=Integer.parseInt(request.getParameter("page"));
			int limit=Integer.parseInt(request.getParameter("limit"));
			int beginrow=(page-1)*limit;
			int endrow=limit;
			
			lst = iUserTempService.GetUsAssTemplateListByWhere(where,beginrow,endrow);
			for (int i = 0; i < lst.size(); i++) {
				lst.get(i).setRowNum(i + 1);
			}
 
			int iCount=iUserTempService.GetUsAssTemplateListCountByWhere(where);
			layTable.setCode(0);
			layTable.setCount(iCount);
			layTable.setData(lst);
			
		} catch (Exception e) {
			layTable.setCode(500);
		}
		return layTable;
	}
	
	
	@LoginCheck(description = true)
	@ResponseBody
	@RequestMapping(value = "/get_user_list")
	public LayTable<UserUsAssTempEntity> GetUserList(HttpServletRequest request) {

		List<UserUsAssTempEntity> lst=null;
		LayTable<UserUsAssTempEntity> layTable=new LayTable<UserUsAssTempEntity>();
		try {
			String realname = request.getParameter("realname");
			
			String templateid = request.getParameter("templateid");
			
			String where="";
			
			String orgids=this.GetOrgListByRole();
			where+=" AND userid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+")";
			
			if(realname!=null&&realname.length()>0){
				where+=" AND realname LIKE '%"+realname+"%' ";
			}
			where+=")";
			if(templateid!=null&&templateid.length()>0){
				where+=" AND templateid="+templateid;
			}
			
		
			
			int page=Integer.parseInt(request.getParameter("page"));
			int limit=Integer.parseInt(request.getParameter("limit"));
			int beginrow=(page-1)*limit;
			int endrow=limit;
			
			lst = iUserTempService.GetUserUsAssTempListByWhere(where, beginrow, endrow);
			for (int i = 0; i < lst.size(); i++) {
				lst.get(i).setRowNum(i + 1);
			}
 
			int iCount=iUserTempService.GetUserUsAssTempListCountByWhere(where);
			layTable.setCode(0);
			layTable.setCount(iCount);
			layTable.setData(lst);
			
		} catch (Exception e) {
			layTable.setCode(500);
		}
		return layTable;
	}
	
	
	
	
	
	@RequestMapping(value = "/add_usertemp")
	public String AddUsertemp(HttpServletRequest request, HttpServletResponse response) {
		try {
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			UsAssTemplateEntity tempentity = new UsAssTemplateEntity();
			
			tempentity.setTemplatename(request.getParameter("templatename"));
			tempentity.setBegintime(Date.valueOf(request.getParameter("begintime")));
			tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
			tempentity.setTemplatedes(request.getParameter("templatedes"));
			tempentity.setByuserid(this.GetLoginUserId());
			tempentity.setGroupid(Long.parseLong(request.getParameter("groupid")));
			tempentity.setSzdw(this.GetLoginUser().getSzdw());
			int iResult=0;
			iResult = iUserTempService.InsertTemplateEntity(tempentity);

			
			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			ex.printStackTrace();
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete_template")
	public ExceResult DeleteTemplate(HttpServletRequest request,HttpServletResponse response){
		ExceResult result=new ExceResult();
		result.setCode(400);
		result.setResult(0);
		try{
		 Long templateid=Long.parseLong(request.getParameter("templateid"));
		 int iResult=iUsAssTemplateService.DeleteUsTempEntity(templateid);
		 if(iResult>0){
				result.setCode(200);
				result.setResult(iResult);
				result.setMsg("操作成功");
			}
			else{
				result.setCode(300);
				result.setResult(iResult);
				result.setMsg("操作失败");
			}
		}
		catch(Exception ex){
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}
	
	
	@RequestMapping(value = "/add_templateindex")
	public String AddTemplateindex(HttpServletRequest request, HttpServletResponse response) {
		try {
			UsAssTemplateIndexEntity entity = new UsAssTemplateIndexEntity();
			if(request.getParameter("assindexid")==null||request.getParameter("assindexid").equals("")){
				entity.setAssindexid(0L);
			}
			else{
				entity.setAssindexid(Long.parseLong(request.getParameter("assindexid")));
			}
			System.out.println(request.getParameter("templateid"));
			entity.setTemplateid(Long.parseLong(request.getParameter("templateid")));
			
			entity.setAssindextype(Integer.parseInt(request.getParameter("assindextype")));
			entity.setByuserid(this.GetLoginUserId());
			entity.setParentid(Long.valueOf(request.getParameter("parentid")));
			entity.setScore(Integer.parseInt(request.getParameter("score")));
			//entity.setTemplateid(Long.valueOf(0));
			entity.setGroupid(Long.valueOf(request.getParameter("groupidsub")));
			if (entity.getAssindextype() == 1) {
				entity.setUassingredients(request.getParameter("uasscontent"));
				entity.setEvaluationstandard(request.getParameter("evaluationstandard"));
			} else {
				entity.setUasscontent(request.getParameter("uasscontent"));
			}

			entity.setSzdw(this.GetLoginUser().getSzdw());
			
			int iResult = 0;
			if(entity.getAssindexid()>0){
				iResult = iUsAssTemplateService.UpdateIndex(entity);
			}
			else{
				if(entity.getParentid()==0){
					entity.setScore(0);
				}
				
				System.out.println(JSON.toJSONString(entity));
				iResult = iUsAssTemplateService.InsertTemplateIndexentity(entity);
			}
			

			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			ex.printStackTrace();
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/delete_index")
	public ExceResult DeleteIndex(HttpServletRequest request,HttpServletResponse response){
		ExceResult result=new ExceResult();
		result.setCode(400);
		result.setResult(0);
		try{
		 Long assindexid=Long.parseLong(request.getParameter("assindexid"));
		 Long parentid=Long.parseLong(request.getParameter("parentid"));
		 int rowspan=Integer.parseInt(request.getParameter("rowspan"));
		 int iResult=iUsAssTemplateService.DeleteIndex(assindexid, parentid);
		 if(iResult>0){
				result.setCode(200);
				result.setResult(iResult);
				result.setMsg("操作成功");
			}
			else{
				result.setCode(300);
				result.setResult(iResult);
				result.setMsg("操作失败");
			}
		}
		catch(Exception ex){
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/get_index_list")
	public List<UsAssTemplateIndexEntity> GetIndexListByOrgid(Long groupid,Long templateid) {
		List<UsAssTemplateIndexEntity> lst=null;
		try
		{
			String where = " AND assindextype=0 AND groupid="+groupid+" AND templateid="+templateid;
			if(this.GetLoginUserId()==0){
				where+=" AND byuserid=0";
			}
			else{
				String orgids=this.GetOrgListByRole();
				where+=" AND byuserid IN (SELECT userid FROM t_sys_user WHERE szdw IN ("+orgids+"))";
			}
			
			lst = iUsAssTemplateService.GetTemplateIndexListByWhere(where);
			return lst;
		}
		catch(Exception ex){
			ex.printStackTrace();
			return null;
		}
	}
	
	
	@RequestMapping(value = "/create_templateindex")
	public String CreateTemplateIndex(HttpServletRequest request, HttpServletResponse response) {
		try {
			String strtemplateid = request.getParameter("templateid");
//			if(strtemplateid==null||strtemplateid.length()<=0){
//				return renderStringScript(response, "<script>window.parent.CloseDialog(0,'参数有误')</script>");
//			}
			
			Long templateid=Long.parseLong(strtemplateid);
			
			
			String parentids = request.getParameter("parentids");
			String assindexids = request.getParameter("assindexids");

			String[] parentidsArr = parentids.split(",");
			String[] assindexidsArr = assindexids.split(",");

			Long flag = 0L;
			List<UsAssTempCreateIndexEntity> lst = new ArrayList<UsAssTempCreateIndexEntity>();
			
			Long byuserid=this.GetLoginUserId();
			int totalScore=0;
			for (int i = 0; i < assindexidsArr.length; i++) {
				//if(request.getParameter("cb_"+ assindexidsArr[i])!=null){
					UsAssTempCreateIndexEntity entity = new UsAssTempCreateIndexEntity();
					entity.setAssindexid(Long.parseLong(assindexidsArr[i]));
					entity.setAssindextype(1);
					entity.setParentid(Long.parseLong(request.getParameter("parentid_" + assindexidsArr[i])));
					entity.setTemplateid(templateid);
					entity.setEvaluationstandard(request.getParameter("evaluationstandard_" + assindexidsArr[i]));
					entity.setScore(Integer.parseInt(request.getParameter("score_" + assindexidsArr[i])));
					entity.setUassingredients(request.getParameter("uassingredients_" + assindexidsArr[i]));
					entity.setUasscontent(request.getParameter("uasscontent_" + entity.getParentid()));
					entity.setByuserid(byuserid);
					totalScore+=entity.getScore();
					lst.add(entity);
				//}
			}
			
			if(totalScore!=100){
				return renderStringScript(response, "<script>window.parent.CloseDialog(0,'总分应为100分')</script>");
			}
			
		if(lst.size()<=0){
			return renderStringScript(response, "<script>window.parent.CloseDialog(0,'请选择指标项')</script>");
		}
			UsAssTemplateEntity tempentity = new UsAssTemplateEntity();
			
			tempentity.setTemplatename(request.getParameter("templatename"));
			tempentity.setBegintime(Date.valueOf(request.getParameter("begintime")));
			tempentity.setEndtime(Date.valueOf(request.getParameter("endtime")));
			tempentity.setTemplatedes(request.getParameter("templatedes"));
			tempentity.setByuserid(byuserid);
			tempentity.setGroupid(Long.parseLong(request.getParameter("groupid")));
			tempentity.setSzdw(this.GetLoginUser().getSzdw());
			int iResult=0;
            if(templateid>0){
            	tempentity.setTemplateid(templateid);
            	//System.out.println(JSON.toJSONString(lst));
            	iResult=iUsAssTemplateService.UpdateUsAssTempEntity(lst, tempentity);
			}
			else{
				iResult = iUsAssTemplateService.CreateTemplateAndIndex(lst, tempentity);
			}

			
			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			ex.printStackTrace();
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/get_list_plyymb")
	public LayTable<UserUsAssTempEntity> GetListPlyymb(HttpServletRequest request) {

		List<UserUsAssTempEntity> lst = null;
		LayTable<UserUsAssTempEntity> layTable = new LayTable<UserUsAssTempEntity>();
		try {
			String realname = request.getParameter("realname");
			String templateid = request.getParameter("templateid");
			String groupid = request.getParameter("groupid");
			String szdw = request.getParameter("szdw");
			String where = "";
			if (realname != null && realname.length() > 0) {
				where += " AND realname LIKE '%" + realname + "%'";
			}
			//where+=" AND groupid="+groupid;
			where+=" AND szdw="+szdw;
			where+=" AND userid NOT IN (SELECT userid FROM t_user_usasstemp WHERE status=1 AND templateid="+templateid+")";
		/*	int page=Integer.parseInt(request.getParameter("page"));
			int limit=Integer.parseInt(request.getParameter("limit"));
			int beginrow=(page-1)*limit;
			int endrow=limit;
			*/
			
			
		
			
			lst = iUserTempService.GetUserGroupListByWhere(where);
			for (int i = 0; i < lst.size(); i++) {
				//int numr=(page-1)*limit+(i + 1);
				int numr=(i + 1);
				lst.get(i).setRowNum(numr);
			}

			int iCount = 0;
			layTable.setCode(0);
			layTable.setCount(iCount);
			layTable.setData(lst);

		} catch (Exception e) {
			layTable.setCode(500);
		}
		return layTable;
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/add_userusasstemp")
	public ExceResult AddUserUsAssTemp(String userids, Long templateid) {
		ExceResult result = new ExceResult();
		result.setCode(400);
		result.setResult(0);
		try {
			
			UsAssTemplateEntity tempentity=iUsAssTemplateService.GetUsAssTemplateListById(templateid);

			List<UserTemplateEntity> list = new ArrayList<UserTemplateEntity>();

			String[] userArr=userids.split(",");
			for(int i=0;i<userArr.length;i++){
				UserTemplateEntity entity=new UserTemplateEntity();
				entity.setUserid(Long.parseLong(userArr[i]));
				entity.setTemplateid(templateid);
				entity.setBegintime(tempentity.getBegintime());
				entity.setEndtime(tempentity.getEndtime());
				list.add(entity);
			}
			
			int iResult = iUserUsAssTempService.InsertBatchEntity(list);

			if (iResult > 0) {
				result.setCode(200);
				result.setResult(iResult);
				result.setMsg("操作成功");
			} else {
				result.setCode(300);
				result.setResult(iResult);
				result.setMsg("操作失败");
			}
		} catch (Exception ex) {
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}
	
}
